package huadi.android.sudoku;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;

public class KeypadDialog extends Dialog implements OnClickListener {

	protected static final String LOG_TAG = "KeypadDialog";

	private final View keys[] = new View[9];
	private View keypad;
	private final int useds[];
	private final PuzzleView puzzleView;

	public KeypadDialog(Context context, int useds[], PuzzleView puzzleView) {
		super(context);
		this.useds = useds;
		this.puzzleView = puzzleView;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.keypad);
		findViews();
		setListeners();
		for (int element : useds) {
			if (element != 0)
				keys[element - 1].setVisibility(View.INVISIBLE);
		}
	}

	/** find button views in keypad */
	private void findViews() {
		keypad = findViewById(R.id.keypad);
		keys[0] = findViewById(R.id.keypad_1);
		keys[1] = findViewById(R.id.keypad_2);
		keys[2] = findViewById(R.id.keypad_3);
		keys[3] = findViewById(R.id.keypad_4);
		keys[4] = findViewById(R.id.keypad_5);
		keys[5] = findViewById(R.id.keypad_6);
		keys[6] = findViewById(R.id.keypad_7);
		keys[7] = findViewById(R.id.keypad_8);
		keys[8] = findViewById(R.id.keypad_9);
	}

	private void setListeners() {
		for (int i = 0; i < keys.length; i++) {
			keys[i].setOnClickListener(this);
		}
		keypad.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				setResult(0);
			}
		});
	}

	private void setResult(int i) {
		this.puzzleView.setSelectedTile(i);
		dismiss();
	}
	
	

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.keypad_1:
			setResult(1);
			break;
		case R.id.keypad_2:
			setResult(2);
			break;
		case R.id.keypad_3:
			setResult(3);
			break;
		case R.id.keypad_4:
			setResult(4);
			break;
		case R.id.keypad_5:
			setResult(5);
			break;
		case R.id.keypad_6:
			setResult(6);
			break;
		case R.id.keypad_7:
			setResult(7);
			break;
		case R.id.keypad_8:
			setResult(8);
			break;
		case R.id.keypad_9:
			setResult(9);
			break;
		}
	}
}
